package com.uni.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.uni.controllers.validation.DisciplineVaildator;
import com.uni.db.GenericService;
import com.uni.domain.Discipline;
@Controller
@RequestMapping("/disciplineEdit.htm")
@SessionAttributes(types = Discipline.class)
public class DisciplineEdit {

    @Autowired
	@Qualifier("disciplineService")
	private GenericService<Discipline> disciplineService;

	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(@RequestParam(value="id", required=false) Long id, ModelMap model) {
		Discipline discipline;
		if (id == null || id < 1){
			discipline = new Discipline();
		} else {
			discipline = disciplineService.get(id);
		}
        model.addAttribute("discipline", discipline);
        return "disciplineEdit";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute Discipline discipline, BindingResult result, SessionStatus status) {
		new DisciplineVaildator().validate(discipline, result);
		if (result.hasErrors()) {
			return "disciplineEdit";
		}
		else {
			disciplineService.save(discipline);
			status.setComplete();
			return "redirect:/discipline/" + discipline.getId();
		}
	}
}
